﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ServerMonitoringAssistantWF
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;

            网站管理ToolStripMenuItem.Click += ToolStripMenuItem_Click;
            重新监控ToolStripMenuItem.Click += ToolStripMenuItem_Click;
            关于ToolStripMenuItem.Click += ToolStripMenuItem_Click;
            安装目录ToolStripMenuItem.Click += ToolStripMenuItem_Click;
            导出网站ToolStripMenuItem.Click += ToolStripMenuItem_Click;
            导入网站ToolStripMenuItem.Click += ToolStripMenuItem_Click;
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (((ToolStripMenuItem)sender).Name)
            {
                case "网站管理ToolStripMenuItem":
                    new FrmSites() { StartPosition = FormStartPosition.CenterScreen }.Show();
                    break;
                case "重新监控ToolStripMenuItem":
                    LoadUI();
                    break;
                case "关于ToolStripMenuItem":
                    new FrmAbout() { StartPosition = FormStartPosition.CenterScreen }.Show();
                    break;
                case "安装目录ToolStripMenuItem":
                    System.Diagnostics.Process.Start(Application.StartupPath);
                    break;
                case "导出网站ToolStripMenuItem":
                    this.Export();
                    break;
                case "导入网站ToolStripMenuItem":
                    this.Import();
                    break;
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            LoadUI();
        }
        private void LoadUI()
        {
            // 清空面板
            /*
            int ctrlcount = layoutMain.Controls.Count;
            if (ctrlcount > 0)
            {
                for (int i = 0; i < ctrlcount; i++)
                {
                    layoutMain.Controls.RemoveAt(i);
                    //layoutMain.Controls[i].Dispose();
                }
                layoutMain.Controls.Clear();
            }*/
            layoutMain.Controls.Clear();
            // 创建数据表
            SqliteMgr.me.ConnectionString = Application.StartupPath + System.IO.Path.DirectorySeparatorChar + "SMADB.db";
            string sqlstmt = "create table if not exists t_sites (id integer primary key AutoIncrement,title varchar(32),url varchar(255) not null default '', remark varchar(255) not null default '', sort integer not null default 0, status integer not null default 1, create_time timestamp not null default current_timestamp)";
            try
            {
                SqliteMgr.me.ExecuteNoneQuery(sqlstmt);
            }
            catch (System.Data.Common.DbException ex)
            {
                MessageBox.Show(ex.Message);
            }
            // 查询站点列表
            sqlstmt = "select * from t_sites where status=1 order by sort, id";
            DataTable dtSites = SqliteMgr.me.ExecuteDataTable(sqlstmt);
            string url;
            int count = dtSites.Rows.Count;
            if (count < 1)
            {
                return;
            }
            DataRow r;
            for (int i = 0; i < count; i++)
            {
                r = dtSites.Rows[i];
                url = DBNull.Value == r["url"] ? string.Empty : r["url"].ToString();
                if (string.IsNullOrEmpty(url))
                {
                    continue;
                }
                MonitoringWindowUC mwin = new ServerMonitoringAssistantWF.MonitoringWindowUC() { Tag = url };
                mwin.SetTitle(r["title"].ToString());
                layoutMain.Controls.Add(mwin);
            }
            for (int i = 0; i < count; i++)
            {
                MonitoringWindowUC mwin = layoutMain.Controls[i] as MonitoringWindowUC;
                mwin.SetUrl(mwin.Tag.ToString(), 30 + i * 5);
            }
        }
        // 导出到文件
        private void Export()
        {
            string sqlstmt = "select title, url, remark from t_sites order by sort, id";
            DataTable dtSites = SqliteMgr.me.ExecuteDataTable(sqlstmt);
            string url;
            int count = dtSites.Rows.Count;
            if (count < 1)
            {
                MessageBox.Show("没有站点记录!", "结果");
                return;
            }
            StringBuilder sbld = new StringBuilder();
            DataRow r;
            for (int i = 0; i < count; i++)
            {
                r = dtSites.Rows[i];
                url = DBNull.Value == r["url"] ? string.Empty : r["url"].ToString();
                if (string.IsNullOrEmpty(url))
                {
                    continue;
                }
                sbld.AppendFormat("{0}||{1}{2}", r["title"], url, Environment.NewLine);
            }
            SaveFileDialog sfd = new SaveFileDialog() { FileName = "网站监控列表", AddExtension = true, DefaultExt = "txt", OverwritePrompt = true, Filter = "文本文件(*.txt)|*.txt" };
            if (DialogResult.OK == sfd.ShowDialog())
            {
                System.IO.File.WriteAllText(sfd.FileName, sbld.ToString());
                if (DialogResult.OK == MessageBox.Show("保存成功,是否打开保存的目录?", "保存结果", MessageBoxButtons.OKCancel))
                {
                    System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(sfd.FileName));
                }
            }
        }
        // 从文件导入
        private void Import()
        {
            OpenFileDialog ofd = new OpenFileDialog() { CheckFileExists=true, Filter = "文本文件(*.txt)|*.txt" };
            if (DialogResult.OK != ofd.ShowDialog())
            {
                return;
            }
            string[] sites=System.IO.File.ReadAllLines(ofd.FileName);
            string[] aitem;
            System.Data.Common.DbParameter[] dbParam = new System.Data.Common.DbParameter[2];
            string sqlstmt = "insert into t_sites (title, url) values (@title,@url)";
            int i = 0;
            if (sites.Length <1)
            {
                MessageBox.Show("文件内容没有包含站点记录!");
                return;
            }
            foreach (string site in sites)
            {
                aitem = site.Split(new char[] {'|','|' },StringSplitOptions.RemoveEmptyEntries);
                if (aitem.Length != 2)
                {
                    continue;
                }
                dbParam[0] = SqliteMgr.me.CreateParameterInputString("@title", aitem[0]);
                dbParam[1] = SqliteMgr.me.CreateParameterInputString("@url", aitem[1]);
                SqliteMgr.me.ExecuteNoneQuery(sqlstmt, dbParam);
                i++;
            }
            MessageBox.Show("导入成功, 成功导入"+i+"条记录!","导入结果");
            this.LoadUI();
        }
    }
}
